const Koa = require('koa')
const app = new Koa()
const onerror = require('koa-onerror')
const koabody = require('koa-body')
const logger = require('koa-logger')
const cors = require('koa-cors')
const parameter = require('koa-parameter')

const index = require('./routes/index')

const host = '127.0.0.1'
const port = 3000

// error handler
onerror(app)

// middlewares
app.use(koabody())
parameter(app)// logger
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(async(ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// 处理跨域
app.use(cors())

// routes
app.use(index.routes(), index.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

app.listen(port, host)
// module.exports = app
